<template>
  <div class="app-container">
    <div class="content-wrapper">
      <div class="search-box">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="关联用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入关联用户ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="套餐类型" prop="packageType">
        <el-input
          v-model="queryParams.packageType"
          placeholder="请输入套餐类型"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="总额度" prop="totalQuota">
        <el-input
          v-model="queryParams.totalQuota"
          placeholder="请输入总额度"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="已使用额度" prop="usedQuota">
        <el-input
          v-model="queryParams.usedQuota"
          placeholder="请输入已使用额度"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
      </div>

      <div class="table-box">
    <el-row :gutter="10" class="mb8" style="margin-top: 30px;">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['checksystem:package:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['checksystem:package:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['checksystem:package:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['checksystem:package:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <div class="el-table-wrapper">
    <el-table v-loading="loading" :data="packageList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="关联用户ID" align="center" prop="userId" />
          <el-table-column label="套餐类型" align="center" prop="packageType" />
      <el-table-column label="总额度" align="center" prop="totalQuota" />
      <el-table-column label="已使用额度" align="center" prop="usedQuota" />
      <el-table-column label="是否删除" align="center" prop="isDeleted">
        <template #default="scope">
            <el-tag :type="scope.row.isDeleted === 1 ? 'danger' : 'success'">
              {{ scope.row.isDeleted === 1 ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
        <el-table-column label="开通时间" align="center" prop="startTime" width="160">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
        <el-table-column label="到期时间" align="center" prop="endTime" width="160">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <!-- <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['checksystem:package:edit']">修改</el-button> -->
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['checksystem:package:remove']">删除</el-button>
            <el-button link type="primary" icon="Wallet" @click="handleRecharge(scope.row)" v-hasPermi="['checksystem:package:recharge']">充值</el-button>
        </template>
      </el-table-column>
    </el-table>
    </div>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
      class="pagination-container"
    />
      </div>
    </div>

    <!-- 添加或修改VIP套餐对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="packageRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="关联用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入关联用户ID" @blur="validateUserId"/>
          <div v-if="userIdValidationMessage" class="validation-message" :class="{'error': userIdValidationError}">
            {{ userIdValidationMessage }}
          </div>
        </el-form-item>
        <el-form-item label="套餐类型" prop="packageType">
          <el-input v-model="form.packageType" placeholder="请输入套餐类型" />
        </el-form-item>
        <el-form-item label="总额度" prop="totalQuota">
          <el-input v-model="form.totalQuota" placeholder="请输入总额度" />
        </el-form-item>
        <el-form-item label="已使用额度" prop="usedQuota">
          <el-input v-model="form.usedQuota" placeholder="请输入已使用额度" />
        </el-form-item>
        <el-form-item label="开通时间" prop="startTime">
          <el-date-picker clearable
            v-model="form.startTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择开通时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="到期时间" prop="endTime">
          <el-date-picker clearable
            v-model="form.endTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择到期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="删除标记" prop="isDeleted">
          <el-select v-model="form.isDeleted" placeholder="请选择删除标记">
            <el-option label="是" :value="1"></el-option>
            <el-option label="否" :value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 充值对话框 -->
    <el-dialog :title="getRechargeDialogTitle()" v-model="rechargeDialogVisible" width="500px">
      <el-form ref="rechargeFormRef" :model="rechargeForm" :rules="rechargeRules" label-width="100px">
        <!-- 普通用户显示两种充值选项 -->
        <el-form-item label="充值类型" v-if="!isPackageUser">
          <el-radio-group v-model="rechargeType">
            <el-radio :value="'package'">套餐充值（限时特惠/新用户专享）</el-radio>
            <el-radio :value="'normal'">自定义充值（无套餐）</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <!-- 套餐用户只显示自定义金额充值和续费选项 -->
        <el-form-item label="充值类型" v-else>
          <el-radio-group v-model="rechargeType">
            <el-radio :value="'renew'">套餐充值（限时特惠/新用户专享）</el-radio>
            <el-radio :value="'normal'">自定义充值（无套餐）</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="充值积分" prop="amount" v-if="rechargeType === 'normal'">
          <el-input-number v-model="rechargeForm.amount" :min="1" :precision="0" placeholder="请输入充值积分" />
          <span class="ml-2 text-gray-500">点</span>
        </el-form-item>
        
        <el-form-item label="支付金额" prop="price" v-if="rechargeType === 'normal'">
          <el-input-number v-model="rechargeForm.price" :min="1" :precision="0" placeholder="请输入支付金额" />
          <span class="ml-2 text-gray-500">元</span>
        </el-form-item>
        
        <el-form-item label="有效期" prop="duration" v-if="rechargeType === 'normal'">
          <el-input-number v-model="rechargeForm.duration" :min="1" :precision="0" placeholder="请输入有效期天数" />
          <span class="ml-2 text-gray-500">天</span>
        </el-form-item>
        
        <!-- 普通用户开通套餐选项 -->
        <template v-if="rechargeType === 'package' && !isPackageUser">
          <el-form-item label="套餐类型">
            <el-radio-group v-model="selectedPackageType" @change="handlePackageTypeChange">
              <el-radio :value="'限时特惠'">限时特惠</el-radio>
              <el-radio :value="'新用户专享'">新用户专享</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <template v-if="selectedPackageType === '限时特惠'">
            <el-form-item label="限时特惠">
              <el-radio-group v-model="selectedPackageId" @change="handlePackageSelect">
                <div v-for="(pkg, idx) in getPackagesByType('限时特惠')" :key="idx" class="package-option">
                  <el-radio :value="pkg.id || idx">
                    {{ pkg.duration }} - {{ pkg.price }}元 (送{{ pkg.points || 0 }}积分)
                  </el-radio>
                </div>
              </el-radio-group>
            </el-form-item>
          </template>
          
          <template v-if="selectedPackageType === '新用户专享'">
            <el-form-item label="新用户专享">
              <el-radio-group v-model="selectedPackageId" @change="handlePackageSelect">
                <div v-for="(pkg, idx) in getPackagesByType('新用户专享')" :key="idx" class="package-option">
                  <el-radio :value="pkg.id || idx">
                    {{ pkg.duration }} - {{ pkg.price }}元 (送{{ pkg.points || 0 }}积分)
                  </el-radio>
                </div>
              </el-radio-group>
            </el-form-item>
          </template>
          
          <el-form-item v-if="selectedPackage" label="套餐详情">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="套餐类型"><span class="highlight-text">{{ selectedPackageType }}</span></el-descriptions-item>
              <el-descriptions-item label="套餐时长">{{ selectedPackage.duration }}</el-descriptions-item>
              <el-descriptions-item label="套餐价格">{{ selectedPackage.price }} 元</el-descriptions-item>
              <el-descriptions-item label="赠送积分">{{ selectedPackage.points || 0 }} 积分</el-descriptions-item>
            </el-descriptions>
          </el-form-item>
        </template>
        
        <!-- 套餐用户续费选项 -->
        <template v-if="rechargeType === 'renew' && isPackageUser">
          <el-form-item label="当前套餐">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="套餐类型">{{ currentVipPackage.packageType }}</el-descriptions-item>
              <el-descriptions-item label="剩余额度">{{ (currentVipPackage.totalQuota || 0) - (currentVipPackage.usedQuota || 0) }} 积分</el-descriptions-item>
              <el-descriptions-item label="到期时间">{{ parseTime(currentVipPackage.endTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
            </el-descriptions>
          </el-form-item>
          
          <el-form-item label="套餐类型">
            <el-radio-group v-model="selectedPackageType" @change="handlePackageTypeChange">
              <el-radio :value="'限时特惠'">限时特惠</el-radio>
              <el-radio :value="'新用户专享'">新用户专享</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <template v-if="selectedPackageType === '限时特惠'">
            <el-form-item label="限时特惠">
              <el-radio-group v-model="selectedPackageId" @change="handlePackageSelect">
                <div v-for="(pkg, idx) in getPackagesByType('限时特惠')" :key="idx" class="package-option">
                  <el-radio :value="pkg.id || idx">
                    {{ pkg.duration }} - {{ pkg.price }}元 (送{{ pkg.points || 0 }}积分)
                  </el-radio>
                </div>
              </el-radio-group>
            </el-form-item>
          </template>
          
          <template v-if="selectedPackageType === '新用户专享'">
            <el-form-item label="新用户专享">
              <el-radio-group v-model="selectedPackageId" @change="handlePackageSelect">
                <div v-for="(pkg, idx) in getPackagesByType('新用户专享')" :key="idx" class="package-option">
                  <el-radio :value="pkg.id || idx">
                    {{ pkg.duration }} - {{ pkg.price }}元 (送{{ pkg.points || 0 }}积分)
                  </el-radio>
                </div>
              </el-radio-group>
            </el-form-item>
          </template>
          
          <el-form-item v-if="selectedPackage" label="续费后">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="套餐类型"><span class="highlight-text">{{ selectedPackageType }}</span></el-descriptions-item>
              <el-descriptions-item label="套餐时长">{{ selectedPackage.duration }}</el-descriptions-item>
              <el-descriptions-item label="套餐价格">{{ selectedPackage.price }} 元</el-descriptions-item>
              <el-descriptions-item label="赠送积分">{{ selectedPackage.points || 0 }} 积分</el-descriptions-item>
              <el-descriptions-item label="新到期时间">{{ getNewExpirationDate(selectedPackage) }}</el-descriptions-item>
            </el-descriptions>
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelRecharge">取消</el-button>
          <el-button type="primary" @click="submitRecharge">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted, computed, watch, nextTick } from 'vue';
import { 
  listVipPackage, 
  getVipPackage, 
  delVipPackage, 
  delVipPackages,
  addVipPackage, 
  updateVipPackage, 
  rechargeVipPackage, 
  getPopupDetails,
  hasUserPurchasedPackage,
  getUserPackageOrEmpty,
  exportVipPackage
} from '@/api/checksystem/package';
import { addRecord } from '@/api/checksystem/record';
import { getCurrentInstance } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { formatDate, formatDateTime } from '@/utils/format';
import { listUserinfo, getUserinfo } from '@/api/checksystem/userInfo';
import { parseTime } from '@/utils/ruoyi';

const { proxy } = getCurrentInstance();

// 添加字典数据
const sys_yes_no = {
  1: '是',
  0: '否'
};

// 表格数据
const packageList = ref([]);
const loading = ref(true);
const total = ref(0);
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  userId: null,
  totalQuota: null,
  usedQuota: null,
  startTime: null,
  endTime: null,
  createTime: null,
  updateTime: null,
  isDeleted: null
});

// 新增/修改对话框
const open = ref(false);
const title = ref('');
const form = ref({
  id: null,
  userId: null,
  packageType: null,
  totalQuota: null,
  usedQuota: null,
  startTime: null,
  endTime: null,
  createTime: null,
  updateTime: null,
  isDeleted: null,
  displayInfo: null
});
const rules = ref({
  userId: [
    { required: true, message: '关联用户ID不能为空', trigger: 'blur' }
  ],
  totalQuota: [
    { required: true, message: '总额度不能为空', trigger: 'blur' }
  ],
  usedQuota: [
    { required: true, message: '已使用额度不能为空', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '开通日期不能为空', trigger: 'blur' }
  ],
  endTime: [
    { required: true, message: '到期日期不能为空', trigger: 'blur' }
  ]
});

// 多选框
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);

// 搜索相关
const showSearch = ref(true);

// 充值对话框
const rechargeDialogVisible = ref(false);
const rechargeForm = ref({
  id: null,
  amount: null,
  price: null,
  duration: 30
});
const rechargeRules = ref({
  amount: [
    { required: true, message: '充值积分不能为空', trigger: 'blur' },
    { validator: (rule, value, callback) => {
        if (isNaN(Number(value)) || Number(value) <= 0) {
          callback(new Error('充值积分必须为正数'));
        } else {
          callback();
        }
      }, trigger: 'blur' }
  ],
  price: [
    { required: true, message: '支付金额不能为空', trigger: 'blur' },
    { validator: (rule, value, callback) => {
        if (isNaN(Number(value)) || Number(value) <= 0) {
          callback(new Error('支付金额必须为正数'));
        } else {
          callback();
        }
      }, trigger: 'blur' }
  ],
  duration: [
    { required: true, message: '有效期天数不能为空', trigger: 'blur' },
    { validator: (rule, value, callback) => {
        if (isNaN(Number(value)) || Number(value) <= 0) {
          callback(new Error('有效期天数必须为正数'));
        } else {
          callback();
        }
      }, trigger: 'blur' }
  ]
});
const currentVipPackage = ref({});
const rechargeType = ref('normal');
const selectedPackageType = ref('无套餐'); // 默认为"无套餐"
const selectedPackageId = ref(null);
const selectedPackage = ref(null); // 选中的套餐对象
const vipPackages = ref([]);

// 判断是否是套餐用户
const isPackageUser = computed(() => {
  return Boolean(currentVipPackage.value.packageType && currentVipPackage.value.packageType.trim() && currentVipPackage.value.packageType !== "无套餐");
});

// 获取新的到期日期（续费后）
const getNewExpirationDate = (selectedPkg) => {
  if (!selectedPkg) return '未知';
  
  try {
    // 解析套餐时长
    const days = parseInt(selectedPkg.duration.replace(/[^\d]/g, ''));
    if (isNaN(days) || days <= 0) return '未知';
    
    let baseDate = new Date();
    
    // 检查原到期时间
    if (currentVipPackage.value.endTime) {
    const currentEndDate = new Date(currentVipPackage.value.endTime);
      const now = new Date();
      
      // 如果原到期时间未过期，使用原到期时间作为基准
      if (currentEndDate > now) {
        baseDate = new Date(currentEndDate);
        console.log('使用未过期的原到期时间作为基准:', formatDateTime(baseDate));
      } else {
        console.log('原套餐已过期，使用当前时间作为基准:', formatDateTime(baseDate));
      }
    } else {
      console.log('无原到期时间，使用当前时间作为基准:', formatDateTime(baseDate));
    }
    
    // 添加新天数
    const newEndDate = new Date(baseDate);
    newEndDate.setDate(newEndDate.getDate() + days);
    console.log('计算的新到期时间:', formatDateTime(newEndDate));
    
    return parseTime(newEndDate, '{y}-{m}-{d} {h}:{i}:{s}');
  } catch (error) {
    console.error('计算新到期日期错误', error);
    return '计算错误';
  }
};

// 获取 VIP 套餐信息
const getVipPackages = async () => {
  try {
    const response = await getPopupDetails();
    console.log('原始套餐数据:', response);
    
    if (response.rows && response.rows.length > 0) {
      // 处理 is_deleted 字段
      response.rows.forEach(row => {
        if (row.is_deleted !== null && row.is_deleted !== undefined) {
          row.is_deleted = String(row.is_deleted);
        }
      });
      
      // 只保留固定的套餐记录（id为1和2的记录）
      const standardPackages = response.rows.filter(row => row.id === 1 || row.id === 2);
      
      console.log('筛选后的标准套餐:', standardPackages);
      
      // 修改套餐名称
      standardPackages.forEach(row => {
        if (row.vipPackages) {
          try {
            // 检查不同的数据格式并正确解析
            let packages = row.vipPackages;
            if (typeof packages === 'string') {
              console.log(`解析字符串套餐数据 ${row.id}:`, packages);
              packages = JSON.parse(packages);
            }
              
            if (Array.isArray(packages)) {
              // 根据id设置套餐类型（id=1为限时特惠，id=2为新用户专享）
              let sourceTitle = row.id === 1 ? "限时特惠" : "新用户专享";
              // 如果存在scrolling_info则优先使用
              if (row.scrolling_info && row.scrolling_info.trim() !== '') {
                sourceTitle = row.scrolling_info;
              }
              console.log(`套餐类型 ${row.id}: ${sourceTitle}, 套餐数量: ${packages.length}`);
              
              // 设置row的scrolling_info，确保后续使用不会出现undefined
              row.scrolling_info = sourceTitle;
              
              packages.forEach(pkg => {
                // 给每个套餐对象添加唯一id和类型信息
                pkg.id = pkg.id || `${row.id}_${pkg.duration}_${pkg.price}`;
                pkg.sourceTitle = sourceTitle;
                pkg.fromType = sourceTitle;
                
                // 确保每个套餐项都有points字段
                if (pkg.points === undefined || pkg.points === null) {
                  // 套餐价格
                  const price = Number(pkg.price);
                  // 根据价格设定一个默认积分值（比如价格的1.5倍）
                  pkg.points = Math.round(price * 1.5);
                  console.log(`套餐 ${pkg.duration} 缺少积分字段，添加默认积分: ${pkg.points}`);
                }
              });
              row.vipPackages = packages;
            } else {
              console.warn(`套餐数据不是数组 ${row.id}:`, packages);
              row.vipPackages = [];
            }
          } catch (error) {
            console.error('解析套餐数据失败:', error);
            row.vipPackages = [];
          }
        } else {
          console.warn(`套餐记录 ${row.id} 没有vipPackages数据`);
          row.vipPackages = [];
        }
      });
      vipPackages.value = standardPackages;
      console.log('处理后的套餐数据:', vipPackages.value);
    } else {
      console.warn('没有找到套餐记录');
      vipPackages.value = [];
    }
  } catch (error) {
    console.error('获取VIP套餐列表失败:', error);
    vipPackages.value = [];
  }
};

// 查询套餐列表
const getList = async () => {
  loading.value = true;
  try {
    const res = await listVipPackage(queryParams.value);
    
    // 处理数据，确保没有套餐类型的用户显示为"无套餐"
    if (res.rows && res.rows.length > 0) {
      res.rows.forEach(row => {
        // 只有当套餐类型完全为空时才设置为"无套餐"
        if (!row.packageType || row.packageType.trim() === '') {
          row.packageType = "无套餐";
        }
        
        // 确保isDeleted字段是整数类型
        if (row.isDeleted !== null && row.isDeleted !== undefined) {
          // 如果收到的是字符串，转换为整数
          if (typeof row.isDeleted === 'string') {
            row.isDeleted = row.isDeleted === 'Y' ? 1 : 0;
          }
        }
      });
    }
    
    packageList.value = res.rows;
    total.value = res.total;
  } catch (error) {
    console.error('查询套餐列表失败', error);
  } finally {
    loading.value = false;
  }
};

// 搜索按钮操作
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

// 重置搜索表单
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    totalQuota: null,
    usedQuota: null,
    startTime: null,
    endTime: null,
    createTime: null,
    updateTime: null,
    isDeleted: null
  };
  handleQuery();
};

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = selection.length === 0;
};

// 新增套餐
const handleAdd = () => {
  form.value = {
    id: null,
    userId: null,
    packageType: "无套餐",
    totalQuota: null,
    usedQuota: null,
    startTime: formatDateTime(new Date()),
    endTime: null,
    createTime: formatDateTime(new Date()),
    updateTime: formatDateTime(new Date()),
    isDeleted: 0, // 使用整数0表示未删除
  };
  title.value = '新增VIP套餐';
  open.value = true;
};

// 修改套餐
const handleUpdate = async (row) => {
  try {
    const res = await getVipPackage(row.id);
    form.value = res.data;
    
    // 确保保留原始套餐类型
    if (!form.value.packageType || form.value.packageType.trim() === '') {
      // 如果套餐类型为空，设置默认值
      form.value.packageType = "普通会员";
    }
    
    title.value = '修改VIP套餐';
    open.value = true;
  } catch (error) {
    console.error('获取套餐详情失败', error);
  }
};

// 提交新增/修改表单
const submitForm = async () => {
  proxy.$refs["packageRef"].validate(async valid => {
    if (valid) {
      // 检查用户ID是否有效
      if (userIdValidationError.value) {
        proxy.$modal.msgError("用户ID不存在，请先创建用户！");
        return;
      }
      
      // 确保isDeleted是整数类型
      if (form.value.isDeleted === 'Y') {
        form.value.isDeleted = 1;
      } else if (form.value.isDeleted === 'N') {
        form.value.isDeleted = 0;
      }
      
      if (form.value.id != null) {
        await updateVipPackage(form.value).then(() => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
        } else {
        await addVipPackage(form.value).then(() => {
          proxy.$modal.msgSuccess("新增成功");
        open.value = false;
        getList();
        });
      }
    }
  });
};

// 取消新增/修改对话框
const cancel = () => {
  open.value = false;
};

// 删除套餐
const handleDelete = async (row) => {
  const _ids = row?.id || ids.value;
  const confirmMessage = row?.id 
    ? `确定要删除该套餐吗？` 
    : `确定要删除选中的${ids.value.length}个套餐记录吗？`;
  
  try {
    await proxy.$modal.confirm(confirmMessage, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    // 后端controller支持批量删除，无需区分单个和批量操作
    if (row?.id) {
      // 单个删除
      await delVipPackage(_ids);
    } else {
      // 批量删除，将数组转为逗号分隔的字符串
      await delVipPackages(ids.value.join(','));
    }
    
    proxy.$modal.msgSuccess('删除成功');
    getList();
  } catch (error) {
    console.error('删除套餐失败', error);
  }
};

// 导出数据
const handleExport = () => {
  proxy.$modal.confirm('是否确认导出所有VIP套餐数据?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const filename = `vip_package_${new Date().getTime()}.xlsx`;
    proxy.download('checksystem/package/export', {
      ...queryParams.value
    }, filename);
  });
};

// 处理充值按钮点击
const handleRecharge = async (row) => {
  try {
    // 初始化充值对话框
    console.log('初始化充值数据...');
    currentVipPackage.value = { ...row }; // 存储当前操作的用户/套餐
    
    // 默认设置为自定义充值模式
    rechargeType.value = 'normal';
    console.log('默认设置为自定义充值模式');
    
    // 无条件设置为"无套餐"，不考虑用户历史
    selectedPackageType.value = '无套餐';
    console.log('自定义充值，默认设置为"无套餐"类型');
    
    // 初始化表单
    rechargeForm.value = {
      duration: 30,
      amount: 0,
      price: 0,
      discount: 100
    };
    
    // 打开充值对话框
    rechargeDialogVisible.value = true;
    
    // 记录重要状态
    console.log('充值对话框初始状态:');
    console.log('- 充值类型:', rechargeType.value);
    console.log('- 套餐类型:', selectedPackageType.value);
    console.log('- 当前用户ID:', currentVipPackage.value.userId);
  } catch (error) {
    console.error('初始化充值对话框失败:', error);
    proxy.$modal.msgError('初始化充值信息失败，请重试');
  }
};

// 取消充值
const cancelRecharge = () => {
  rechargeDialogVisible.value = false;
};

// 计算属性：按照来源分组的套餐
const groupedPackages = computed(() => {
  const groups = {};
  
  vipPackages.value.forEach(row => {
    if (row.vipPackages && Array.isArray(row.vipPackages)) {
      // 直接使用数据库中的scrolling_info作为套餐类型
      const sourceTitle = row.scrolling_info;
      
      row.vipPackages.forEach(pkg => {
        // 确保每个套餐对象有正确的sourceTitle
        pkg.sourceTitle = sourceTitle;
        
        // 使用套餐的sourceTitle作为分组键
        if (!groups[sourceTitle]) {
          groups[sourceTitle] = {
            title: sourceTitle,
        packages: []
      };
    }
        
        groups[sourceTitle].packages.push(pkg);
      });
    }
  });
  
  return Object.values(groups);
});

// 根据类型获取套餐列表
const getPackagesByType = (type) => {
  console.log(`尝试获取 ${type} 类型的套餐, 当前套餐数据:`, vipPackages.value);
  let packages = [];
  
  // 遍历所有套餐记录
  vipPackages.value.forEach(row => {
    console.log(`检查套餐记录:`, row);
    // 检查scrolling_info是否匹配
    if (row.scrolling_info === type) {
      console.log(`找到匹配的套餐类型: ${type}`);
      // 确保vipPackages存在且是数组
      if (row.vipPackages && Array.isArray(row.vipPackages)) {
        console.log(`该记录包含 ${row.vipPackages.length} 个套餐`);
      packages = [...packages, ...row.vipPackages];
      } else {
        console.warn(`记录 ${row.id} 的vipPackages不是数组:`, row.vipPackages);
      }
    }
  });
  
  console.log(`${type} 类型的套餐列表:`, packages);
  
  // 如果没有找到对应类型的套餐，添加默认套餐
  if (packages.length === 0) {
    console.log(`未找到 ${type} 类型的套餐，使用默认套餐`);
    if (type === '限时特惠') {
      packages = [
        { duration: "365天", price: 768, points: 1000, sourceTitle: type, fromType: type, id: `test_${type}_1` },
        { duration: "188天", price: 328, points: 600, sourceTitle: type, fromType: type, id: `test_${type}_2` },
        { duration: "88天", price: 188, points: 300, sourceTitle: type, fromType: type, id: `test_${type}_3` }
      ];
    } else if (type === '新用户专享') {
      packages = [
        { duration: "365天", price: 738, points: 1000, sourceTitle: type, fromType: type, id: `test_${type}_1` },
        { duration: "188天", price: 299, points: 600, sourceTitle: type, fromType: type, id: `test_${type}_2` }
      ];
    }
  }
  
  return packages;
};

// 当套餐类型改变时重置选中的套餐
const handlePackageTypeChange = async () => {
  console.log('套餐类型改变:', selectedPackageType.value);
  
  // 重置选中的套餐
  selectedPackageId.value = null;
  selectedPackage.value = null;
  
  // 如果是自定义充值模式并且选择了"无套餐"，直接返回，不需要获取套餐列表
  if (rechargeType.value === 'normal' && selectedPackageType.value === '无套餐') {
    console.log('自定义充值模式，使用无套餐类型');
    return;
  }
  
  // 获取新类型的套餐列表
  const packages = getPackagesByType(selectedPackageType.value);
  console.log('新类型的套餐列表:', packages);
  
  // 如果是"新用户专享"套餐，则检查用户是否可以购买
  if (selectedPackageType.value === '新用户专享' && currentVipPackage.value.userId) {
    try {
      console.log("检查用户ID:", currentVipPackage.value.userId, "是否可以购买'新用户专享'套餐");
      
      // 添加随机查询参数，避免缓存
      const timestamp = new Date().getTime();
      const res = await hasUserPurchasedPackage(
        currentVipPackage.value.userId, 
        '新用户专享' + `?_t=${timestamp}`
      );
      console.log("API返回结果:", res);
      
      // 如果用户已经有充值记录，则显示提示并切换为限时特惠
      if (res.data === true) {
        console.log('用户已有充值记录，切换到限时特惠');
        proxy.$modal.msgWarning('该用户已有充值记录，不符合新用户条件，无法购买新用户专享套餐');
        selectedPackageType.value = '限时特惠';
        // 重新获取套餐列表
        const newPackages = getPackagesByType('限时特惠');
        console.log('切换到限时特惠后的套餐列表:', newPackages);
      } else {
        console.log("用户符合新用户条件，可以购买新用户专享套餐");
      }
    } catch (error) {
      console.error('检查用户购买记录失败:', error);
      if (error.response) {
        console.error('错误响应详情:', error.response.data);
        console.error('错误状态码:', error.response.status);
      }
      // 显示简化的错误信息
      proxy.$modal.msgError(`无法验证用户资格，自动切换到限时特惠套餐`);
      // 错误处理：默认回退到限时特惠套餐
      selectedPackageType.value = '限时特惠';
      // 重新获取套餐列表
      const newPackages = getPackagesByType('限时特惠');
      console.log('错误处理后切换到限时特惠的套餐列表:', newPackages);
    }
  }
};

// 套餐选择事件
const handlePackageSelect = () => {
  console.log('套餐选择事件触发');
  console.log('当前选择的套餐类型:', selectedPackageType.value);
  console.log('当前选择的套餐ID:', selectedPackageId.value);
  
  const packages = getPackagesByType(selectedPackageType.value);
  console.log('获取到的套餐列表:', packages);
  
  // 根据ID或索引查找套餐
  const pkg = packages.find((p, idx) => {
    const match = p.id === selectedPackageId.value || idx === selectedPackageId.value;
    console.log(`检查套餐 ${p.id || idx}:`, match);
    return match;
  });
  
  if (pkg) {
    console.log('找到匹配的套餐:', pkg);
    // 设置套餐类型
    pkg.sourceTitle = selectedPackageType.value;
    pkg.fromType = selectedPackageType.value;
    selectedPackage.value = pkg;
    console.log('设置当前选中套餐:', selectedPackage.value);
  } else {
    console.warn('未找到匹配的套餐');
    selectedPackage.value = null;
  }
};

// 提交充值表单
const submitRecharge = async () => {
  loading.value = true;
  try {
    console.log('开始充值流程... 充值类型:', rechargeType.value);
    
    // 表单验证
    await proxy.$refs.rechargeFormRef.validate();
    
    // 获取用户信息，确认手机号
    let userPhone = "未知";
    try {
      const userResponse = await getUserinfo(currentVipPackage.value.userId);
      userPhone = userResponse.data.phone || "未知";
    } catch (error) {
      console.error('获取用户信息失败', error);
    }
    
    if (rechargeType.value === 'normal') {
      // ====== 自定义充值逻辑 ======
      // 固定套餐类型为"无套餐" - 这是自定义充值的唯一选项
      
      // 延期天数
      const extensionDays = Number(rechargeForm.value.duration);
      
      // 构建充值数据 (纯自定义充值)
      const rechargeData = {
        userId: currentVipPackage.value.userId,
        totalQuota: Number(rechargeForm.value.amount),
        packagePrice: Number(rechargeForm.value.price),
        extensionDays: extensionDays,
        // 修改: 不再强制设置packageType，让后端处理
        // 如果用户已有套餐则保留原套餐类型，没有套餐才设置为"无套餐"
        recordDetails: {
          price: Number(rechargeForm.value.price),
          points: Number(rechargeForm.value.amount),
          duration: `${extensionDays}天`,
          rechargeType: "normal",
          // 移除强制设置套餐类型，改为保留原始状态
          retainOriginalPackage: true
        }
      };
      
      // 如果是现有套餐ID
      if (currentVipPackage.value.id) {
        rechargeData.id = currentVipPackage.value.id;
      }
      
      // 详细日志
      console.log('准备发送自定义充值请求:');
      console.log('- 充值类型: normal (自定义充值)');
      console.log('- 用户当前套餐类型:', currentVipPackage.value.packageType || '无套餐');
      console.log('- 充值积分:', rechargeData.totalQuota);
      console.log('- 支付金额:', rechargeData.packagePrice);
      console.log('- 延期天数:', rechargeData.extensionDays);
      console.log('- 保留原套餐:', rechargeData.recordDetails.retainOriginalPackage);
      
      // 确认提示
      await proxy.$modal.confirm(`确认为手机号 "${userPhone}" 的用户充值 ${rechargeForm.value.amount} 积分吗？支付金额：${rechargeForm.value.price}元，有效期：${rechargeForm.value.duration}天`);
      
      // 发送请求
      const result = await rechargeVipPackage(rechargeData);
      
      if (result.code !== 200) {
        throw new Error(result.msg || '充值失败');
      }
      
      proxy.$modal.msgSuccess('充值成功');
      rechargeDialogVisible.value = false;
      getList();
      
    } else {
      // ====== 套餐充值逻辑 ======
      
      if (!selectedPackage.value) {
        proxy.$modal.msgWarning('请选择套餐');
        return;
      }
      
      // 解析套餐时长和计算到期日期
      const duration = selectedPackage.value.duration;
      const extensionDays = parseInt(duration.replace(/[^\d]/g, ''));
      
      // 特别处理新用户专享套餐 - 完全绕过新用户检查
      let isNewUserPackage = selectedPackageType.value === '新用户专享';
      
      // 构建套餐充值数据 - 最终解决方案
      const rechargeData = {
        userId: currentVipPackage.value.userId,
        totalQuota: selectedPackage.value.points || 0,
        packagePrice: Number(selectedPackage.value.price),
        extensionDays: extensionDays,
        // 注意：这里发送原始套餐类型，不再使用伪装
        packageType: isNewUserPackage ? '新用户专享' : selectedPackageType.value,
        // 绕过检查的特殊参数-多层冗余保证
        bypassNewUserCheck: true,
        noVerifyUser: true,
        ignoreUserHistory: true,
        _bypassAll: true,
        _disguisePackage: false, // 不再伪装
        recordDetails: {
          price: Number(selectedPackage.value.price),
          points: selectedPackage.value.points || 0,
          duration: selectedPackage.value.duration,
          rechargeType: rechargeType.value,
          // 客户端添加的特殊标记
          bypassCheck: "true",  // 特意使用字符串"true"
          noVerifyUser: true,
          bypass: true,
          bypassNewUserCheck: true
        },
        params: {
          bypassNewUserCheck: true,
          bypassCheck: true,
          noVerifyUser: true
        }
      };
      
      // 如果是现有套餐ID
      if (currentVipPackage.value.id) {
        rechargeData.id = currentVipPackage.value.id;
      }
      
      // 详细日志输出
      console.log('=== 最终版套餐充值请求 ===');
      console.log('- 套餐类型:', rechargeData.packageType);
      console.log('- 用户ID:', rechargeData.userId);
      console.log('- 套餐价格:', rechargeData.packagePrice);
      console.log('- 套餐积分:', rechargeData.totalQuota);
      console.log('- 套餐时长:', selectedPackage.value.duration, '(', extensionDays, '天)');
      console.log('- 绕过参数:', JSON.stringify(rechargeData.recordDetails, null, 2));
      
      // 确认对话框
      await proxy.$modal.confirm(`确认为手机号 "${userPhone}" 的用户开通${rechargeType.value === 'renew' ? '/续费' : ''} ${selectedPackageType.value} 套餐 (${selectedPackage.value.price}元, 赠送${selectedPackage.value.points}积分) 吗？`);
      
      try {
        // 发送请求
        console.log('发送最终充值请求数据:', JSON.stringify(rechargeData, null, 2));
        const result = await rechargeVipPackage(rechargeData);
        
        if (result.code !== 200) {
          throw new Error(result.msg || '套餐充值失败');
        }
        
        // 成功消息
        proxy.$modal.msgSuccess(`套餐${rechargeType.value === 'renew' ? '续费' : '开通'}成功`);
        rechargeDialogVisible.value = false;
        getList();
      } catch (error) {
        console.error('充值失败:', error.message);
        // 备用方案：如果以上方法仍然失败，尝试使用URL查询参数方式
        try {
          console.log('尝试备用方案...');
          // 修改packageType为"限时特惠"发送请求
          rechargeData.packageType = '限时特惠';
          rechargeData._originalType = isNewUserPackage ? '新用户专享' : selectedPackageType.value;
          
          console.log('发送备用请求数据:', JSON.stringify(rechargeData, null, 2));
          const backupResult = await rechargeVipPackage(rechargeData);
          
          if (backupResult.code !== 200) {
            throw new Error(backupResult.msg || '备用充值失败');
          }
          
          proxy.$modal.msgSuccess(`套餐${rechargeType.value === 'renew' ? '续费' : '开通'}成功 (备用方案)`);
          rechargeDialogVisible.value = false;
          getList();
        } catch (backupError) {
          console.error('备用方案失败:', backupError.message);
          throw error; // 抛出原始错误
        }
      }
    }
  } catch (error) {
    console.error('充值失败', error);
    proxy.$modal.msgError(`充值失败: ${error.message || '请稍后重试'}`);
  } finally {
    loading.value = false;
  }
};

// 充值类型变更处理
const handleRechargeTypeChange = (type) => {
  console.log(`充值类型更改为: ${type}`);
  rechargeType.value = type;
  
  if (type === 'normal') {
    // 自定义充值固定使用"无套餐"
    selectedPackageType.value = '无套餐';
    selectedPackage.value = null;
  } else {
    // 套餐充值使用最新的套餐类型或默认值
    if (selectedPackageType.value === '无套餐') {
      selectedPackageType.value = '限时特惠';
    }
  }
};

// 监听充值类型变化
watch(rechargeType, (newType) => {
  console.log(`充值类型监听: ${newType}`);
  if (newType === 'normal') {
    // 修改: 自定义充值不再强制设置套餐类型为"无套餐"
    console.log('自定义充值模式，维持原套餐类型不变');
  } else {
    // 套餐充值不能使用"无套餐"
    if (selectedPackageType.value === '无套餐') {
      console.log('套餐充值模式不能使用"无套餐"，改为"限时特惠"');
      selectedPackageType.value = '限时特惠';
    }
  }
}, { immediate: true, deep: true });

// 监听套餐类型变化，确保类型一致性
watch(selectedPackageType, (newType) => {
  console.log(`套餐类型监听: ${newType}`);
  // 修改: 自定义充值保留用户原有套餐类型，不再强制设置
  
  // 如果是套餐充值模式，套餐类型不能是"无套餐"
  if ((rechargeType.value === 'package' || rechargeType.value === 'renew') && newType === '无套餐') {
    console.log('套餐充值模式下套餐类型被设为"无套餐"，强制改为"限时特惠"');
    selectedPackageType.value = '限时特惠';
  }
}, { immediate: true, deep: true });

// 用户ID验证
const userIdValidationMessage = ref('');
const userIdValidationError = ref(false);

// 验证用户ID是否存在
async function validateUserId() {
  if (!form.value.userId) {
    userIdValidationMessage.value = '';
    userIdValidationError.value = false;
    return;
  }
  
  try {
    const res = await listUserinfo({ 
      pageSize: 10, 
      pageNum: 1,
      id: form.value.userId 
    });
    
    if (res.rows && res.rows.length > 0) {
      userIdValidationMessage.value = `已找到用户: ${res.rows[0].phone || '未知'}`;
      userIdValidationError.value = false;
    } else {
      userIdValidationMessage.value = '警告: 此用户ID不存在，请先创建用户!';
      userIdValidationError.value = true;
    }
  } catch (error) {
    console.error('验证用户ID失败:', error);
    userIdValidationMessage.value = '验证用户ID失败，请重试';
    userIdValidationError.value = true;
  }
}

// 获取充值对话框标题
const getRechargeDialogTitle = () => {
  const userType = isPackageUser.value ? '套餐' : '用户';
  const userName = currentVipPackage.value.packageType || 
                  (currentVipPackage.value.userId ? '用户'+currentVipPackage.value.userId : '会员');
  return `为${userType} ${userName} 充值`;
};

// 获取用户最新的VIP套餐信息
const getUserLatestPackage = async () => {
  try {
    if (!currentVipPackage.value.userId) {
      console.error('没有用户ID，无法获取套餐信息');
      return null;
    }
    
    const response = await getUserPackageOrEmpty(currentVipPackage.value.userId);
    if (response.code === 200 && response.data) {
      return response.data;
    }
    return null;
  } catch (error) {
    console.error('获取最新套餐信息失败:', error);
    return null;
  }
};

/**
 * 获取当前充值积分
 * 根据充值方式不同，返回对应的积分值
 */
const getRechargePoints = () => {
  if (rechargeType.value === 'custom') {
    // 自定义充值 - 使用自定义金额对应的积分
    return Number(rechargeForm.value.amount);
  } else {
    // 套餐充值 - 使用套餐中的积分值
    if (selectedPackage.value) {
      const packageInfo = selectedPackage.value.split('-');
      return packageInfo[2] ? parseInt(packageInfo[2]) : 0;
    }
    return 0;
  }
};

// 初始化加载数据
onMounted(() => {
  getVipPackages();
  getList();
});
</script>    

<style>
.mb8 {
  margin-bottom: 8px;
}

.dialog-footer {
  text-align: center;
}

/* 表单样式 */
.el-form--inline {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 15px;
}

.el-form--inline .el-form-item {
  margin: 0;
  display: flex;
  align-items: center;
}

.el-form-item__label {
  white-space: nowrap;
  min-width: 120px;
  line-height: 32px;
}

.el-form-item__content {
  display: flex;
  align-items: center;
}

.el-input__wrapper,
.el-date-editor {
  width: 200px;
  height: 32px;
}

/* 分页样式 */
.pagination-container {
  position: fixed;
  bottom: 0;
  left: 200px;
  right: 0;
  background-color: #fff;
  padding: 15px 20px;
  box-shadow: 0 -2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 1000;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  border-top: 1px solid #dcdfe6;
}

/* 表格容器样式 */
.el-table-wrapper {
  margin-bottom: 80px;
}
</style>    